import pg from 'pg';
import bcryptjs from 'bcryptjs';
import path from 'path';
import { fileURLToPath } from 'url';
import dotenv from 'dotenv';
import { dirname } from 'path';

const { Pool } = pg;
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// 加载环境变量
dotenv.config({ path: path.resolve(process.cwd(), '.env') });

// 创建数据库连接池
const pool = new Pool({
  user: String(process.env.PG_USER || ''),
  password: String(process.env.PG_PASSWORD || ''),
  host: String(process.env.PG_HOST || 'localhost'),
  port: parseInt(process.env.PG_PORT || '5432', 10),
  database: String(process.env.PG_DATABASE || ''),
  ssl: process.env.PG_SSL === 'true' ? true : false
});

async function addUser() {
  try {
    // 查询现有最大用户ID
    const maxIdResult = await pool.query(`
      SELECT MAX(id) as max_id FROM users
    `);
    let lastId = 0;
    if (maxIdResult.rows.length > 0 && maxIdResult.rows[0].max_id) {
      lastId = parseInt(maxIdResult.rows[0].max_id, 10);
      // 重置序列到最大ID
      await pool.query(`
        SELECT setval('users_id_seq', $1, true)
      `, [lastId]);
      console.log(`检测到数据库最大用户ID: ${lastId}, 新用户将从ID ${lastId + 1} 开始创建`);
    }
    // 用户信息
    const username = 'root';
    const password = 'root';
    
    // 检查用户是否已存在
    const checkResult = await pool.query(
      'SELECT id FROM users WHERE username = $1',
      [username]
    );

    if (checkResult.rows.length > 0) {
      console.log(`用户 ${username} 已存在`);
      return;
    }

    // 加密密码
    const hashedPassword = await bcryptjs.hash(password, 10);
    
    // 创建新用户
    const insertResult = await pool.query(
      'INSERT INTO users (username, password, created_at, updated_at) VALUES ($1, $2, NOW(), NOW()) RETURNING id, username',
      [username, hashedPassword]
    );
    console.log('用户创建成功:', insertResult.rows[0]);

    // 创建测试用户
    const testUsername = 'test';
    const testPassword = 'test123';
    const testHashedPassword = await bcryptjs.hash(testPassword, 10);
    
    const testInsertResult = await pool.query(
      'INSERT INTO users (username, password, created_at, updated_at) VALUES ($1, $2, NOW(), NOW()) RETURNING id, username',
      [testUsername, testHashedPassword]
    );
    
    console.log('测试用户创建成功:', testInsertResult.rows[0]);
    
  } catch (error) {
    console.error('添加用户失败:', error);
  } finally {
    await pool.end();
  }
}

addUser(); 